//
//  XPOAuthViewController.m
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/13.
//  Copyright © 2016年 徐攀. All rights reserved.
//

#import "XPOAuthViewController.h"


@interface XPOAuthViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;

@end

@implementation XPOAuthViewController

- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
        _webView.delegate = self;
    }
    return _webView;
}

- (void)loadView {
    self.view = self.webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigationBar];
    
    NSString *URLString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",kClientId,kRedirectUri];
    
    [self loadWebViewWithURL:URLString];
}

- (void)loadWebViewWithURL:(NSString *)URLString {
    NSURL *URL = [NSURL URLWithString:URLString];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    [self.webView loadRequest:request];
}

- (void)setupNavigationBar {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[self buttonWithTitle:@"取消" action:@selector(cancelBtnClick)]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[self buttonWithTitle:@"自动填充" action:@selector(autoFill)]];
}

- (UIButton *)buttonWithTitle:(NSString *)title action:(SEL)selector {
    return [UIButton baseButton:title withFontSize:16 backgroundImage:nil target:self action:selector];
}

- (void)cancelBtnClick {
    [self dismissViewControllerAnimated:self completion:nil];
}

- (void)autoFill {
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('userId').value = '1373814735@qq.com'; document.getElementById('passwd').value = 'ajdd1314'"];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSString *URLString = request.URL.absoluteString;
    
    if (![URLString hasPrefix:kRedirectUri]) {
        return YES;
    }
    
    NSString *query = request.URL.query;
    NSString *code = [query substringFromIndex:([query rangeOfString:@"code="].length + [query rangeOfString:@"code="].location)];
    
    [[XPNetworkTools sharedTool] requestAccessToken:code finishedBlock:^(BOOL isSuccess) {
        if (isSuccess) {
            NSLog(@"授权成功");
            [SVProgressHUD dismiss];
        }else{
            NSLog(@"授权失败");
            [SVProgressHUD dismiss];
        }
    }];
    return NO;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [SVProgressHUD dismiss];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [SVProgressHUD show];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [SVProgressHUD dismiss];
}
@end
